const fs = require("fs");
const path = require("path");

const cwd = path.resolve(__dirname, "..");
const candidates = [
  path.join(cwd, "node_modules", "ethers", "dist", "ethers.min.js"),
  path.join(cwd, "node_modules", "ethers", "dist", "ethers.umd.min.js"),
  path.join(cwd, "node_modules", "ethers", "dist", "ethers.umd.js"),
  path.join(cwd, "node_modules", "ethers", "lib", "ethers.min.js"),
];

let found = null;
for (const p of candidates) {
  if (fs.existsSync(p)) {
    found = p;
    break;
  }
}

const destDir = path.join(cwd, "app", "public", "libs");
const dest = path.join(destDir, "ethers.min.js");

if (!found) {
  console.warn(
    "ethers build file not found in node_modules. Please ensure `npm install` completed and ethers is installed."
  );
  console.warn("Tried paths:\n" + candidates.join("\n"));
  process.exit(0);
}

if (!fs.existsSync(destDir)) fs.mkdirSync(destDir, { recursive: true });

fs.copyFileSync(found, dest);
console.log("Copied", found, "->", dest);
